package com.peanut.baby.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.peanut.baby.InitManager;
import com.peanut.devlibrary.LibContext;
import com.peanut.devlibrary.util.DeviceInfo;
import com.peanut.devlibrary.util.StringUtil;
import com.tencent.mars.xlog.Log;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;


/**
 * Created by taransky on 16/3/15.
 */
public class DevicesUtils {

    public static void initDevicesInfos(){
        DeviceInfo info = new DeviceInfo();

        info.appversion = getAppVersion();

        DisplayMetrics metrics = InitManager.getInstance().getCtx().getResources().getDisplayMetrics();
        info.screen = metrics.widthPixels+"_"+metrics.heightPixels;

        try {
            initDeviceNetworkInfos(info);
        } catch (Exception e) {
            Log.d("DevicesUtils","initDeviceNetworkInfos exception: "+e.toString());
        }


        try {
            TelephonyManager tm = (TelephonyManager) InitManager.getInstance().getCtx().getSystemService(Context.TELEPHONY_SERVICE);
            if(tm != null){
                info.uuid = tm.getDeviceId();
            }

            if(StringUtil.isNullOrEmpty(info.uuid)){
                if(!StringUtil.isNullOrEmpty(info.mac)){
                    info.uuid = info.mac;
                }
            }

            if(StringUtil.isNullOrEmpty(info.uuid)){
                if(!StringUtil.isNullOrEmpty(info.mac)){
                    info.uuid = android.provider.Settings.Secure.getString(
                            LibContext.getInstance().getContext().getContentResolver(),
                            android.provider.Settings.Secure.ANDROID_ID);
                }
            }
        } catch (Exception e) {
            Log.d("DevicesUtils","initDevice info exception: "+e.toString());
            info.uuid = "android";
        }



        InitManager.getInstance().info = info;
        Log.d("DevicesUtils",info.toString());

    }

    public static void initDevicesInfosWithoutPermission(){
        DeviceInfo info = new DeviceInfo();

        info.appversion = getAppVersion();

        DisplayMetrics metrics = InitManager.getInstance().getCtx().getResources().getDisplayMetrics();
        info.screen = metrics.widthPixels+"_"+metrics.heightPixels;

        InitManager.getInstance().info = info;
        Log.d("DevicesUtils",info.toString());

    }

    private static void initDeviceNetworkInfos(DeviceInfo info){

        Context incontext = InitManager.getInstance().getCtx().getApplicationContext();
        ConnectivityManager conManager = (ConnectivityManager) incontext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
        if (networkInfo != null) {
            //ip address
            if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI){
                //wifi状态
                info.network = DeviceInfo.NETWORK_WIFI;
                info.ip = getWifiIpAddress();
                info.mac = getMacAddress();
            }else if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){
                //数据流量状态
                String _strSubTypeName = networkInfo.getSubtypeName();

                Log.d("TAG","_strSubTypeName: "+_strSubTypeName);

                // TD-SCDMA   networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
                        info.network = DeviceInfo.NETWORK_2G;
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD:  //api<11 : replace by 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP:  //api<13 : replace by 15
                        info.network = DeviceInfo.NETWORK_3G;
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE:    //api<11 : replace by 13
                        info.network = DeviceInfo.NETWORK_4G;
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000"))
                        {
                            info.network = DeviceInfo.NETWORK_3G;
                        }
                        else
                        {
                            info.network = _strSubTypeName;
                        }

                        break;
                }


                info.ip = getLocalIpAddress();

            }

        }


    }

    /**
     * 获取wifi下ip地址
     * @return
     */
    private static String getWifiIpAddress() {
        WifiManager wifiManager = (WifiManager) InitManager.getInstance().getCtx().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        // 获取32位整型IP地址
        int ipAddress = wifiInfo.getIpAddress();

        //返回整型地址转换成“*.*.*.*”地址
        return String.format("%d.%d.%d.%d",
                (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
                (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
    }

    private static String getMacAddress() {
        WifiManager wifi = (WifiManager) InitManager.getInstance().getCtx().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }


    /**
     * 获取非wifi下ip地址
     * @return
     */
    private static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && inetAddress instanceof Inet4Address) {
                        // if (!inetAddress.isLoopbackAddress() && inetAddress
                        // instanceof Inet6Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String getAppVersion(){
        String appVersion = "";
        PackageManager manager = InitManager.getInstance().getCtx().getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(InitManager.getInstance().getCtx().getPackageName(),0);
            appVersion = info.versionName; //版本名
        } catch (PackageManager.NameNotFoundException e) {
            //
            e.printStackTrace();
            appVersion = "";
        }
        return appVersion;
    }


    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = tm.getDeviceId();

            String mac = null;
            FileReader fstream = null;
            try {
                fstream = new FileReader("/sys/class/net/wlan0/address");
            } catch (FileNotFoundException e) {
                fstream = new FileReader("/sys/class/net/eth0/address");
            }
            BufferedReader in = null;
            if (fstream != null) {
                try {
                    in = new BufferedReader(fstream, 1024);
                    mac = in.readLine();
                } catch (IOException e) {
                } finally {
                    if (fstream != null) {
                        try {
                            fstream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
